package com.project.common.screens;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.InputFilter;
import android.text.method.PasswordTransformationMethod;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.project.trac.R;

import core.modules.DatabaseConnector;
import core.modules.Institute;

public class Login extends Institute {

	private ResultSet rs;

	private EditText inputUsername;
	private EditText inputPassword;
	private EditText inputCode;

	private Dialog dialog;
	private AlertDialog.Builder alertDialog;
	private ProgressDialog progressDialog;

	private TextView msg;
	private TextView create;
	private TextView spiel;
	private View layout;

	// String required for login
	private String INPUT_USERNAME;
	private String INPUT_PASSWORD;
	private String INPUT_CODE;
	int ctr = 0;

	private String USERNAME;
	private String PASSWORD;
	private String IDENTIFIER;
	private String command = "command";
	    
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.commons_login);
		setTitle("Welcome to TRAC!");

		final CheckBox showPassword = (CheckBox) findViewById(R.id.showpassword);
		final Button btnLogin = (Button) findViewById(R.id.buttonLogin);

		// Custom Dialog Layout
		layout = View.inflate(getApplicationContext(), R.layout.generic_dialog_box, null);
		inputCode = (EditText) layout.findViewById(R.id.dialogInput);
		spiel = (TextView) layout.findViewById(R.id.dialogSpiel);
		create = (TextView) findViewById(R.id.createStudentAccount);
		spiel.setText("For faculty members,\nan authorization code is required.");
		
		inputCode.setFilters(new InputFilter[] { 
			    new InputFilter.LengthFilter(6) // 150 is max length
		});
		
		progressDialog = new ProgressDialog(Login.this);
		alertDialog = new AlertDialog.Builder(Login.this);
		msg = new TextView(this);

		alertDialog.setTitle("Information").setIcon(android.R.drawable.ic_dialog_info);
		alertDialog.setCancelable(true);

		msg.setTextAppearance(this, R.style.alert_message);
		msg.setGravity(Gravity.CENTER_HORIZONTAL);

		// Pre-check for connectivity
//		if (!isNetworkConnected()) {
//			msg.setText("Please check Wifi hardware availability");
//			alertDialog.setView(msg)
//			.setCancelable(false)
//			.setPositiveButton(android.R.string.ok,
//					new DialogInterface.OnClickListener() {
//				public void onClick(DialogInterface dialog,int id) {
//					Login.this.finish();
//				}
//			}).create().show();
//		} else if (!isWifiAvailable() && !isNetworkConnected()) {
//		msg.setText("An internet connection is required to login!");
//		alertDialog.setView(msg)
//		.setPositiveButton(android.R.string.ok,
//				new DialogInterface.OnClickListener() {
//			// TODO invoke fix wifi setting
//			public void onClick(DialogInterface dialog, int id) {
//				dialog.dismiss();
//			}
//		}).create().show();
//			
//		} else if (isWifiAvailable() && isNetworkConnected()) {
			new AsynchronousTask().execute("validate");
//		}


			/** - - - - - New User - - - - -  */
		alertDialog.setPositiveButton("I'm a teacher!", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int id) {
				INPUT_CODE = inputCode.getText().toString();
				if (IDENTIFIER.equals(INPUT_CODE)) {
					inputCode.setText("");
					setRole(0);
					startActivity(new Intent(Login.this, Registration.class));
					
				} else {
					Toast.makeText(getBaseContext(), "Invalid faculty code.", Toast.LENGTH_LONG).show();
					inputCode.setText("");
					ctr++;
					if (ctr == 3) {
						msg.setText("Invalid faculty code for 3 times, \n system shutdown");
						alertDialog.setTitle("Alert!");
						alertDialog.setIcon(android.R.drawable.ic_dialog_alert);
						alertDialog.setView(msg);
						alertDialog.setNegativeButton(android.R.string.ok,new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface arg0, int arg1) {
								finish();
							}
						});

					}
				} //end if-else
			}
		});
		alertDialog.setNegativeButton("I'm a student!", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int id) {
				INPUT_CODE = inputCode.getText().toString();
				if (INPUT_CODE.isEmpty()) {
					startActivity(new Intent(Login.this, Registration.class));
					setRole(1);
				} else {
					Toast.makeText(getBaseContext(), "No need for a faculty code.", Toast.LENGTH_LONG).show();
					inputCode.setText("");
					dialog.cancel();
				}
			}
		});

		dialog = alertDialog.setTitle("New Registration").setView(layout).create();

		create.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				dialog.show();
			}
		});

		showPassword.setOnClickListener(new OnClickListener() {

			public void onClick(View arg0) {
				if (((CheckBox) showPassword).isChecked()) {
					inputPassword.setTransformationMethod(null);
				} else {
					inputPassword.setTransformationMethod(new PasswordTransformationMethod());
				}
			}
		});

		/** - - - - - Login - - - - - */
		inputUsername = (EditText) findViewById(R.id.editusername);
		inputPassword = (EditText) findViewById(R.id.editpassword);

		// TODO:
		inputUsername.setText("gma");
		inputPassword.setText("a");
		
		btnLogin.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				INPUT_USERNAME =  inputUsername.getText().toString();
				INPUT_PASSWORD = inputPassword.getText().toString();

				List<EditText> e = new ArrayList<EditText>();
				e.add(inputPassword);
				e.add(inputUsername);

				for (EditText et : e) {
					if (et.getText().toString().length() <= 0) {
						et.setError("required");
					}
					
					if (et.getText().toString().length() > 0) {
						et.setError(null);
					}
				}

				new AsynchronousTask().execute("login");
				command = "login";

			}
		});

	}

	@Override
	public void onSaveInstanceState(Bundle outState) {
		outState.putString("WORKAROUND_FOR_BUG_19917_KEY", "WORKAROUND_FOR_BUG_19917_VALUE");
		super.onSaveInstanceState(outState);
	}

	private long lastPress;
	@Override
	public void onBackPressed() {

		long currentTime = System.currentTimeMillis();
		if (currentTime - lastPress > 3500) {
			Toast.makeText(getBaseContext(), "Press back again to exit.", Toast.LENGTH_LONG).show();
			lastPress = currentTime;
		} else {
			finish();
		}

		if (dialog.isShowing()) {
			this.inputCode.setText("");
		}
	}

	@Override
	public void onAttachedToWindow() {
		super.onAttachedToWindow();
		Window window = getWindow();
		window.setFormat(PixelFormat.RGBA_8888);
	}
	
	
	public static String getLocalIpAddress() {
	    try {
	        for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
	            NetworkInterface intf = en.nextElement();
	            for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
	                InetAddress inetAddress = enumIpAddr.nextElement();
	                if (!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet4Address) {
	                    return inetAddress.getHostAddress();
	                }
	            }
	        }
	    } catch (SocketException ex) {
	        ex.printStackTrace();
	    }
	    return null;
	}

	private class AsynchronousTask extends AsyncTask<String, String, String> {

		protected void onPreExecute() {
			super.onPreExecute();
			if (command.equalsIgnoreCase("login")) {
				progressDialog.setMessage("logging in...");
			} else {
				progressDialog.setMessage("please wait...");
			}

			progressDialog.setIcon(android.R.drawable.ic_dialog_info);
			progressDialog.setIndeterminate(true);
			progressDialog.setCancelable(true);
			progressDialog.show();

		}

		protected String doInBackground(String... args) {

			try {

				if (args[0].equalsIgnoreCase("validate")) {
					rs = DatabaseConnector.getStatement().executeQuery("SELECT * FROM code");
					while (rs.next()) {
						IDENTIFIER = rs.getString("identifier");
					}
				} else if (args[0].equalsIgnoreCase("login")) {
					
					rs = DatabaseConnector.getStatement().executeQuery
							("SELECT id, FirstName, username, password, isstudent FROM users WHERE username = '" 
							 + INPUT_USERNAME + "' AND password = '" + INPUT_PASSWORD + "'");

					if (rs.next()) {
						USERNAME = rs.getString("username");
						PASSWORD = rs.getString("password");

						if (USERNAME.equalsIgnoreCase(INPUT_USERNAME)) {
							if (PASSWORD.equalsIgnoreCase(INPUT_PASSWORD)) {
								setRole(rs.getInt("isStudent"));
								setUsername(rs.getString("username"));
								setPassword(rs.getString("password"));
								setFirstName(rs.getString("FirstName"));
								setUserID(rs.getString("id"));

							    DatabaseConnector.getConnection().setAutoCommit(false);
								DatabaseConnector.setPreparedStatement("UPDATE users SET IP= \"" + getLocalIpAddress() + "\", PORT=15145 WHERE id = " + getUserID() + ";");
								PreparedStatement set = DatabaseConnector.getPreparedStatement();
								set.executeUpdate();
									
								set.close();
							    startActivity(new Intent(Login.this, Dashboard.class));
						    	finish();
								
							} else {	// else password
								ctr++;
								Toast.makeText(getBaseContext(),"Invalid password.", Toast.LENGTH_LONG).show();
								if (ctr == 3) {
									msg.setText("Incorrect password input (3x)!, \n application will close.");
									alertDialog.setTitle("Alert!");
									alertDialog.setIcon(android.R.drawable.ic_dialog_alert);
									alertDialog.setView(msg);
									alertDialog.setNegativeButton(android.R.string.ok, new DialogInterface.OnClickListener() {
										@Override
										public void onClick(DialogInterface arg0, int arg1) {
											finish();
										}
									});

								}
							} // end if-password check
							rs.close();
							}
						} else {		// else username
							Toast.makeText(getBaseContext(),"No such username!", Toast.LENGTH_LONG).show();
						}
					}
					

			} catch (SQLException e) {
				DatabaseConnector.Logger(getClass(), "doInBackground", e);
			}

			return null;
		}

		protected void onPostExecute(String postExecute) {
			if (progressDialog.isShowing()) {
				progressDialog.dismiss();
			}

		}
	}
	
}